package display.screens {
	
	import events.ScreenEvent;
	
	import fl.controls.Button;
	import fl.controls.ComboBox;
	import fl.controls.DataGrid;
	import fl.controls.dataGridClasses.DataGridColumn;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextFormat;
	
	import org.ilovecode.screen.Screen;
	import org.ilovecode.screen.ScreenName;
	
	import utils.Utilities;
	
	/**
	 * Screen which is used to search for apartments by user defined criteria.
	 * 
	 * @author Vjekoslav Ratkajec
	 */
	public class SearchScreen extends Screen {
		
		//{ region Stage elements
		
		//ComboBox to choose size as criteria
		public var sizeComboBox:ComboBox;
		//ComboBox to choose floor as criteria
		public var floorComboBox:ComboBox;
		//Button to commit database search
		public var searchButton:Button;
		//Warning which will be shown if no results are found
		public var warning:MovieClip;
		//Datagrid which will contain search results
		public var datagrid:DataGrid;
		
		//} endregion
		
		//{ region Variables
		
		//Number of loaded ComboBox elements, so that after all are loaded, results may be loaded
		private var numComboBoxesLoaded:int = 0;
		
		//} endregion
		
		//{ region Constructor and intialization
		
		/**
		 * Create instance of Search screen.
		 */
		public function SearchScreen() {
			super(ScreenName.SEARCH, "searchScreen");
		}
		
		override protected function initUI():void
		{
			super.initUI();
			
			//Load ComboBoxes with data
			Utilities.loadURL("http://www.ban-centar.hr/xml/codelist/areaintervallist", loadSizeComboBox);
			Utilities.loadURL("http://www.ban-centar.hr/xml/codelist/floorlist", loadFloorComboBox);
			
			warning.visible = false;
			
			//Initialize datagrid
			datagrid.addEventListener(Event.CHANGE, dataGridChange);
			datagrid.visible = false;
			datagrid.removeAll();
			formatDataGrid();
		}
		
		override protected function addListeners():void
		{
			super.addListeners();
			sizeComboBox.addEventListener(Event.CHANGE, dataChange);
			floorComboBox.addEventListener(Event.CHANGE, dataChange);
			searchButton.addEventListener(MouseEvent.CLICK, searchButtonClick);
		}
		
		override protected function removeListeners():void
		{
			super.removeListeners();
			sizeComboBox.removeEventListener(Event.CHANGE, dataChange);
			floorComboBox.removeEventListener(Event.CHANGE, dataChange);
			searchButton.removeEventListener(MouseEvent.CLICK, searchButtonClick);
		}
		
		
		//} endregion
		
		//{ region Loading
		
		/**
		 * Fill loaded data in ComboBox.
		 * 
		 * @param	event	Loading sizes data is completed.
		 * @private
		 */
		private function loadSizeComboBox(event:Event):void {
			loadComboBoxData(XML(event.target.data), sizeComboBox);
			numComboBoxesLoaded++;
			checkIfAllComboBoxesAreLoaded();
		}
		
		/**
		 * Fill loaded data in ComboBox.
		 * 
		 * @param	event	Loading floors data is completed.
		 * @private
		 */
		private function loadFloorComboBox(event:Event):void {
			loadComboBoxData(XML(event.target.data), floorComboBox);
			numComboBoxesLoaded++;
			checkIfAllComboBoxesAreLoaded();
		}
		
		/**
		 * Fill data in ComboBox and set first item as active.
		 * 
		 * @param	xml	XML list of data which will fill ComboBox.
		 * @param	cb	ComboBox which will be loaded with data.
		 * @private
		 */
		private function loadComboBoxData(xml:XML, cb:ComboBox):void {
			var sve:Object = new Object();
			sve.label = sve.data = "sve";
			cb.addItem(sve);
			for each(var item:XML in xml.children()) {
				var o:Object = new Object();
				o.label = item.name;
				o.data = item.id;
				cb.addItem(o);
			}
			if (cb.numChildren > 0) {
				cb.selectedIndex = 0;
			}
		}
		
		/**
		 * Check if all ComboBoxes are loaded, and if so, load results for default values.
		 * @private
		 */
		private function checkIfAllComboBoxesAreLoaded():void {
			if (numComboBoxesLoaded >= 2) {
				loadResults();
			}
		}
		
		//} endregion
		
		//{ region Load results
		
		/**
		 * Load results from server by user defined criteria.
		 * 
		 * @private
		 */
		private function loadResults():void {
			var url:String =  "http://www.ban-centar.hr/xml/search/" + floorComboBox.selectedItem.data + "/" + sizeComboBox.selectedItem.data;
			Utilities.loadURL(url, loadResultsComplete);
		}
		
		/**
		 * Format datagrid position, look and columns.
		 * 
		 * @private
		 */
		private function formatDataGrid():void {
			datagrid.width = 800 - 250;
			datagrid.height = 530 - 275;
			datagrid.move(105, 220);
			datagrid.rowHeight=25;
			datagrid.resizableColumns = true;
			var formatGrid:TextFormat = new TextFormat();
			formatGrid.color = 0x000000;
			formatGrid.size = 14;
			datagrid.setRendererStyle("textFormat",formatGrid);
			datagrid.setStyle("fontFamily", "Verdana");
			datagrid.setStyle("headerColor", "0xA6CBDD");
			datagrid.setStyle("alternatingRowColors", ["0xF0F0F0", "0xFFFFFF"]);
			datagrid.setStyle("rollOverColor", "0xDCEBF1");
			datagrid.setStyle("selectionColor", "0xFFF97D");
			datagrid.setStyle("selectionDuration", 300);
			datagrid.blendMode = "normal";
			
			var colA:DataGridColumn = new DataGridColumn("Površina");
			var colB:DataGridColumn = new DataGridColumn("Kat");
			//var colC:DataGridColumn = new DataGridColumn("Broj soba");
			var colD:DataGridColumn = new DataGridColumn("Šifra");
			var colE:DataGridColumn = new DataGridColumn("Id");
			colE.visible = false;
			datagrid.addColumn(colA);
			datagrid.addColumn(colB);
			//datagrid.addColumn(colC);
			datagrid.addColumn(colD);
			datagrid.addColumn(colE);
		}
		
		/**
		 * Show loaded results in datagrid.
		 * If there are no results, datagrid is hidden, and warning shown.
		 * 
		 * @param	event	Loading results completed.
		 * @private
		 */
		private function loadResultsComplete(event:Event):void {
			var xml:XML = XML(event.target.data);
			
			if (xml.children().length() > 0) {
				warning.visible = false;
				for each(var item:XML in xml.children()) {
					var o:Object = new Object();
					o["Šifra"] = item.code;
					o["Kat"] = item.floor;
					//o["Broj soba"] = item.roomsnumber;
					o["Površina"] = item.area;
					o["Id"] = item.id;
					datagrid.addItem(o);
				}
				datagrid.visible = true;
			} else {
				warning.visible = true;
			}
		}
		
		//} endregion
		
		//{ region Handlers
		
		/**
		 * When row in datagrid is changed (selected), dispatch event to show apartment details.
		 * 
		 * @param	event	User selected row in datagrid.
		 * @private
		 */
		private function dataGridChange(event:Event):void {
			//TODO: Impelement searching result functionality
			/*var o:Object = new Object();
			o.apartmentID = datagrid.selectedItem.Id;
			o.floorID = getFloorNumber(datagrid.selectedItem.Kat);
			this.dispatchEvent(new ScreenEvent(ScreenEvent.SWITCH_SCREEN, o));*/
			
			controller.showApartment(datagrid.selectedItem.Id);
		}
		
		/**
		 * ComboBox selected item has been changed, so hide results (or warining).
		 * When selected item has changed, user must manually request results by clicking on search button.
		 * 
		 * @param	event	ComboBox selected item has been changed.
		 * @private
		 */
		private function dataChange(event:Event):void {
			if (datagrid.visible) {
				datagrid.visible = false;
				warning.visible = false;
			}
		}
		
		/**
		 * Remove current results and start loading results.
		 * 
		 * @param	event	Search button has been clicked.
		 * @private
		 */
		private function searchButtonClick(event:MouseEvent):void {
			if (sizeComboBox.selectedIndex != -1 && floorComboBox.selectedIndex != -1) {
				datagrid.removeAll();
				loadResults();
			}
		}
		
		//} endregion
		
		//{ region Helpers
		
		/**
		 * Convert floor name to floor number.
		 * 
		 * @param	floorName	Floor name.
		 * @return	Floor number.
		 * @private
		 */
		private function getFloorNumber(floorName:String):int {
			var floorNumber:int = -1;
			switch(floorName.toLowerCase()) {
				case "prizemlje":
					floorNumber = 0;
					break;
				case "prvi kat":
					floorNumber = 1;
					break;
				case "drugi kat":
					floorNumber = 2;
					break;
				case "treći kat":
					floorNumber = 3;
					break;
				case "četvrti kat":
					floorNumber = 4;
					break;
				case "peti kat":
					floorNumber = 5;
					break;
				case "šesti kat":
					floorNumber = 6;
					break;
				case "sedmi kat":
					floorNumber = 7;
					break;
				case "osmi kat":
					floorNumber = 8;
					break;
			}
			
			return floorNumber;
		}
		
		//} endregion
		
	}
	
}